<template>
  <div class="score-card-setting"
       id="score-card-setting">
    <el-form ref="lineSetting"
             :model="setting"
             label-position="top"
             style="height:auto;">
      <el-form-item :label="$t('custom.component.gadget.yValue')">
        <el-select v-model="setting.fields"
                   :placeholder="$t('placeholder.psyv')"
                   clearable
                   style="width:80%;"
                   @change="selectFieldsChange">
          <el-option v-for="(item,index) in dataSourceColumns"
                     :key="index"
                     :label="item.name"
                     :value="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('custom.component.gadget.xValue')">
        <el-select v-model="setting.valueFieldsX"
                   :placeholder="$t('placeholder.psxv')"
                   clearable
                   style="width:80%;"
                   @change="selectvalueFieldsXChange">
          <el-option v-for="(item,index) in dataSourceX"
                     :key="index"
                     :label="item.name"
                     :value="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('custom.component.gadget.user')">
        <select-client-user-info v-model="setting.userId"
                                 :width="80"
                                 @ChangeClientUserInfo="userChange"></select-client-user-info>
      </el-form-item>
      <el-form-item :label="$t('custom.component.gadget.refreshCron')">
        <el-select v-model="setting.refreshCron"
                   :placeholder="$t('custom.component.gadget.refreshCronPlaceholder')"
                   clearable
                   :style="{width:cronArr.includes(setting.refreshCron)?'50%': '80%'}">
          <el-option v-for="(item,index) in cronList"
                     :key="index"
                     :label="item.dictLabel"
                     :value="item.dictValue"></el-option>
        </el-select>
        <el-time-select style="width:30%" v-if="cronArr.includes(setting.refreshCron)"
                        v-model="setting.num"
                        :picker-options="{
            start: '00:00',
            step: '00:05',
            end: '23:59'
          }">
        </el-time-select>
      </el-form-item>
      <el-form-item label="Time Zone">
        <el-select v-model="setting.timezoneId"
                   filterable
                   clearable
                   default-first-option style="width: 80%">
          <el-option v-for="item in timezoneList"
                     :key="item"
                     :label="item"
                     :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('custom.component.gadget.benchmark')">
        <el-input v-model="setting.benchMark" style="width:80%;"></el-input>
      </el-form-item>
      <el-form-item :label="$t('custom.component.gadget.dateRange')">
            <el-date-picker
              v-model="setting.dateRange"
              type="datetimerange"
              style="width:80%;"
              range-separator="-"
              @change="changeDateRange"
              :start-placeholder="$t('placeholder.sdate')"
              :end-placeholder="$t('placeholder.edate')"
              align="left">
            </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('custom.component.gadget.headerText')">
        <el-input v-model="setting.heading" style="width:80%;"></el-input>
      </el-form-item>
      <el-form-item label="Showing date interval">
        <el-input v-model="setting.dateInterval" style="width:80%;"></el-input>
      </el-form-item>
      <el-form-item :label="$t('custom.component.gadget.showTrendLine')">
        <el-select clearable size="small" v-model="setting.showTrendLine" :placeholder="$t('custom.component.gadget.placeholder')" style="width:80%;">
          <el-option v-for="(item,index) in trendLineList" :key="index"  :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import Index from '../../dashboard-filter/index.vue'
import { TimeZoneNameList } from '@/utils'
import moment from 'moment'
export default {
  name: 'ScoreCardSetting',
  components: { Index },
  data () {
    return {
      dataSource: [],
      timezoneList: TimeZoneNameList(),
      setting: {
        headerTitle: '',
        headerDescription: '',
        wikiUrl: '',
        datasetLimit: '',
        datasetOrderBy: [],
        fields: [],
        valueFieldsX: 'snapshot_date',
        refreshCron: '',
        timezoneId: '',
        userId: '',
        userName: '',
        benchMark: '',
        dateRange: [],
        drillThroughStatus: true,
        heading: '',
        dateInterval: '',
        showTrendLine: '',
        headUrl: '',
        everyDayAt: false,
        lastDays: '',
        radio: 'daterange',
        num: '',
        refreshCronStr: '',
      },
      trendLineList: ['linear', 'exponential', 'polynomial'],
      cronArr: ['Specific time on Last Day of the Month','Every Day At', '0 0 0 ? * SUN *', '0 0 0 ? * MON *', '0 0 0 ? * TUE *', '0 0 0 ? * WED *', '0 0 0 ? * THU *', '0 0 0 ? * FRI *', '0 0 0 ? * SAT *'],
      num: '00:00'
    }
  },
  props: [
    'data', 'fieldsList'
  ],
  watch: {
    'setting.userId' (val) {
      if (!val) {
        this.setting.userName = ''
      }
    },
    data (value, oldValue) {
      return this.updateSetting(value)
    }
  },
  created () {
    if (this.data) {
      this.$set(this.data)
    }
  },
  computed: {
    cronList () {
      try {
        return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'cron_expression_list').dataList
      } catch (error) {
        return []
      }
    },
    dataSourceX(){
      const arr = this.fieldsList.filter(item =>item.type === 'datetime' || item.type === 'date' ) || []    
      arr.push({name:'snapshot_date'})  
      return this._.uniqBy(arr, 'name')
    },
    dataSourceColumns(){
      return this.fieldsList
    },
    
  },
  methods: {
    isCron (val) {
      const arr = val.split('?')
      if (arr.length > 1) {
        return this.cronArr.includes(arr[1].trim())
      }
      return false
    },
    changeHander (val) {
      this.setting.everyDayAt = val === 'Every Day At' || val === 'Specific time on Last Day of the Month'
      this.setting.everyDayAt ? this.setting.refreshCronStr = val : this.setting.refreshCronStr = ''
    },
    getData () {
      if (this.cronArr.includes(this.setting.refreshCron)) {
        let numArr = 0
        if (this.setting.num) {
          numArr = this.setting.num.split(':')
          if (this.setting.refreshCron === 'Every Day At') {
            this.setting.refreshCron = `0 ${Number(numArr[1])} ${Number(numArr[0])} * * ? *`
          } else if (this.setting.refreshCron === 'Specific time on Last Day of the Month') {
            this.setting.refreshCron = `0 ${Number(numArr[1])} ${Number(numArr[0])} L * ?`
          } else {
            let arr = this.setting.refreshCron.split('')
            arr[2] = Number(numArr[1])
            arr[4] = Number(numArr[0])
            this.setting.refreshCron = arr.join('')
          }
        }
      }
      if (!this.setting.timezoneId) {
        this.setting.timezoneId = this.$store.state.user.timezoneId
      }
      return this.setting
    },
    selectFieldsChange (val) {
      // field is Array, multiple need update
      if (val) {        
        if (val === 'id' || val === 'Id' || val === 'iD' || val === 'ID') {
          this.setting.fields = []
          return this.$message.error("Y Value cannot equal 'id', 'Id', 'iD' and 'ID'")
        }else{
          this.setting.fields = [val]
        }
        this.$forceUpdate()
      }
    },
    selectvalueFieldsXChange (val) {
      // field is Array, multiple need update
      if (val) {
        this.setting.valueFieldsX = val
        this.$forceUpdate()
      }
    },
    userChange (item) {
      if (item && item.id) {
        this.setting.userId = item.id
        this.setting.userName = item.realName
        this.setting.headUrl = item.headUrl
        this.$forceUpdate()
      } else {
        this.setting.userId = ''
        this.setting.userName = ''
        this.setting.headUrl = ''
        this.$forceUpdate()
      }
    },
    changeDateRange (val) {
      if (val) {
        this.setting.dateRange = [this.fromatUtcDate(val[0]), this.fromatUtcDate(val[1])]
      } else {
        this.setting.dateRange = []
      }
    },
    fromatUtcDate (date) {
      if (date) {
        return moment.tz((moment(date).format()), this.$store.state.user.timezoneId).utc().format()
      }
    },
    updateSetting (value, list, layerStatus) {
      if (value.gadgetSetting.everyDayAt) {
        if (value.gadgetSetting.refreshCron !== 'Every Day At' || value.gadgetSetting.refreshCron !== 'Specific time on Last Day of the Month' ) {
          this.num = value.gadgetSetting.refreshCron.split(' ')[2]
          if (this.num > 9) {
            this.num = `${this.num}:00`
          } else {
            this.num = `0${this.num}:00`
          }
          value.gadgetSetting.refreshCron = value.gadgetSetting.refreshCronStr?value.gadgetSetting.refreshCronStr:'Every Day At'
          this.setting.num = this.num
        }
      }
      // TODO 临时解决方案
      const cronSplit = value.gadgetSetting.refreshCron.split('?')
      if (cronSplit[1] && cronSplit[1] !== ' *' && this.cronArr.join('').includes(cronSplit[1]) && (value.gadgetSetting.refreshCron !== 'Every Day At' && value.gadgetSetting.refreshCron !== 'Specific time on Last Day of the Month') ) {
        this.cronArr.map(item => {
          if (item.includes(value.gadgetSetting.refreshCron.split('?')[1])) {
            value.gadgetSetting.refreshCron = item
          }
        })
      }
      this._.merge(this.setting, value.gadgetSetting)
      this.setting.dateRange = Array.isArray(this.setting.dateRange) && this.setting.dateRange[0] && this.setting.dateRange[0] !== 'undefined' ? [unescape(this.setting.dateRange[0]), unescape(this.setting.dateRange[1])] : []
      if (value && value.gadgetSetting && !layerStatus) {

      } else if (value && list) {

      }
      this.$emit('update:data', this.setting)
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss">
.score-card-setting {
  .column-card {
    margin-top: 8px;
  }
  .el-card__body {
    padding: 5px 20px !important;
  }
  .column-field {
    font-weight: bold;
  }
  .column-type {
    color: #9ea1a7;
  }
  .column-link {
    float: left;
    border: none;
    margin-left: 3px;
  }
  .el-form-item .el-form-item {
    margin-bottom: 4px;
  }
}
</style>
<style scoped>
::v-deep .el-range-editor.el-input__inner {
  padding: 0 10px;
}
</style>
